<?php
namespace app\common\server;
use x\Xbase;
class OrderGoods extends Xbase
{

    /**创建订单
     * @param $user_id 用户ID
     * @param $goods_ids 购物车商品ID数组
     * @param $order_no 订单编号
     * @param $address_id 地址ID
     * @param $goods_type 商品类型
     * @param $invitecode 最后分享人邀请码
     * @param $note 订单备注
     */
    public  function add($user_id,$address_id,$goods_ids,$invitecode=0,$isUsepoints=false,$totalPoint=0,$note=''){
        $address_info = $this->db->query("select * from user_address where id = ? and user_id = ?",[$address_id,$user_id],1);
        $user_info = $this->db->query("select * from user where id = ? ",[$user_id],1);
        if(!$address_info){
            return $this->setError('地址不存在!');
        }
        $use_point = 0;
        if($totalPoint > $user_info['money_jf']){
            $use_point = $user_info['money_jf'];
        }else{
            $use_point = $totalPoint;
        }
        //库存判断
        $map = [
          ['and','a.id','in', array_keys($goods_ids)]
        ];
        $w = where($map);
        $sql = "select
                    a.*,b.title as goods_name,b.pic,b.postage,b.shop_id,b.point,b.get_point
                from
                    goods_price a
                left join
                    goods b
                on
                    a.goods_id = b.id " . $w[0];
        $rs = $this->db->query($sql,$w[1]);
        if(!$rs){
            return $this->setError('商品不存在!');
        }
        foreach ($rs as $k => $v) {
            foreach ($goods_ids as $k1 => $v1) {
                if($v['id']== $k1 && $v["stock"] < $v1){
                    return $this->setError('库存不足！');
                }
            }
        }
        $address = $address_info['province'].$address_info['city'].$address_info['district'].$address_info['address'];
        //创建订单
        $data = [];
        $total_money = 0;
        $total_points = 0;
        $total_use_points = 0;
        $total_postage = 0;
        $total_lingshou = 0;
        $total_pifa = 0;
        $total_daili = 0;
        $total_gulijin = 0;
        $order_no = $this->com_order_no();
        $this->db->begin();
        $mysql = [];
        #订单编号数组
        $temp = [];
        foreach ($rs as $k => $v) {
            $points = 0;
            if($isUsepoints){
                if($use_point > $v['point']*$goods_ids[$v['id']]){//如果抵扣的积分大于商品需要抵扣的积分
                    $points = $v['point']*$goods_ids[$v['id']];
                    $use_point -= $v['point']*$goods_ids[$v['id']];
                }else{
                    $points = $use_point;
                    $use_point = 0;
                }
            }
            $d = [
                "user_id" => $user_id,
                "goods_price_id" => $v["id"],
                "goods_id" => $v["goods_id"],
                "shop_id" => $v["shop_id"],
                "order_no" => $order_no.$v["shop_id"],
                "title" => $v["goods_name"],
                "goods_price_title" => $v["title"],
                "pic" => $v["pic"],
                "goods_price_price" => $v["price"],
                "sh_name" => $address_info['address_name'],
                "sh_address" => $address,
                "sh_phone" => $address_info['address_phone'],
                "nums" => $goods_ids[$v['id']],
                "total_money" => ($v["price"]+$v['postage'])*$goods_ids[$v['id']],
                "postage" => $v['postage']*$goods_ids[$v['id']],
                "lingshou_money" => $v['lingshou_money']*$goods_ids[$v['id']],
                "pifa_money" => $v['pifa_money']*$goods_ids[$v['id']],
                "daili_money" => $v['daili_money']*$goods_ids[$v['id']],
                "gulijin_money" => $v['gulijin_money']*$goods_ids[$v['id']],
                "points" => $v['get_point']*$goods_ids[$v['id']],
                "use_points" => $points,
                "create_time" => time(),
                "note" => $note,
            ];
            $temp[] = $d['order_no'];
            $this->db->query('delete from order_cart where user_id = ? and goods_price_id = ?',[$user_id,$v['id']]);
            $data[] = $d;
            $total_money += $d['total_money'];
            $total_postage += $d['postage'];
            $total_points += $d['points'];
            $total_use_points += $d["use_points"];
            $total_lingshou += $d['lingshou_money'];
            $total_pifa += $d['pifa_money'];
            $total_daili += $d['daili_money'];
            $total_gulijin += $d['gulijin_money'];
        }
        $mysql[] = $this->db->insertAll('order_goods',$data);

        #记录订单临时表
        $temp_data = [];
        $invitecode = $invitecode?de_id($invitecode):0;
        if (!$invitecode) {
            $invitecode = $user_info['relation_id'];
        }
        foreach($data as $v){
            if(!isset($temp_data[$v['order_no']])) $temp_data[$v['order_no']]=[];
            $temp_data[$v['order_no']] = [
                'order_no' => $v['order_no'],
                'user_id' => $v['user_id'],
                'gulijin_user_id' => $invitecode,
                "title" => $v["title"],
                "goods_price_title" => $v["goods_price_title"],
                "pic" => $v["pic"],
                'order_total_money' => $total_money,
                'order_total_points' => $total_points,
                'order_total_use_points' => $total_use_points,
                'order_total_postage' => $total_postage,
                'order_total_lingshou' => $total_lingshou,
                'order_total_pifa' => $total_pifa,
                'order_total_daili' => $total_daili,
                'order_total_gulijin' => $total_gulijin,
                'create_time' => time()
            ];
        }
        $mysql[] = $this->db->insertAll('order_goods_no',$temp_data);

        $result = $this->db->end($mysql);
        if(!$result){
            return $this->setError('创建订单失败!');
        }
        #返回订单编号数组
        return array_filter($temp);
    }

    /**
     * 确认收货
     * @param  [type] $user_id  [description]
     * @param  [type] $order_no [description]
     * @return [type]     [description]
     */
    public function finish($user_id,$order_no){
        $order_goods_no = $this->db->query("select * from order_goods_no where order_no = ?", [$order_no],1);
        if($order_goods_no['status'] >= 4 ) return $this->setError("该订单已确认收货!");

        $order = $this->db->query('select * from order_goods where order_no=? and user_id=?',[$order_no,$user_id]);
        if(!$order) return $this->setError("订单不存在!");

        #是否存在退货订单
        $goods_ids = [];
        $refund_ids = [];
        $refund_money = 0;
        $refund_points = 0;
        $refund_use_points = 0;
        $refund_postage = 0;

        $refund_lingshou = 0;
        $refund_pifa = 0;
        $refund_daili = 0;
        $refund_gulijin = 0;
        foreach ($order as $v) {
            if ( $v['refund_status']==2 ) {
                $refund_ids[] = $v['id'];
                $refund_money += $v['total_money'];
                $refund_points += $v['points'];
                $refund_use_points += $v['use_points'];
                $refund_postage += $v['postage'];
                $refund_lingshou += $v['lingshou_money'];
                $refund_pifa += $v['pifa_money'];
                $refund_daili += $v['daili_money'];
                $refund_gulijin += $v['gulijin_money'];
            }else{
                if ($v['fahuo_status']==0) {
                    return $this->setError("订单ID[{$v['id']}]未发货!");
                }
                $goods_ids[] = $v['id'];
            }
        }

        $mysql = [];
        $com_order_no = $this->com_order_no();
        $this->db->begin();

        if ($goods_ids) {
            $map = [
                ['and','id', 'in', $goods_ids]
            ];
            $w = where($map);
            $mysql[] = $this->db->query("update order_goods set sh_status=1 {$w[0]}",$w['1']);
            $map = [
                ['and','refund_status', '=', 1],
                ['and','id', 'in', $goods_ids]
            ];
            $w = where($map);
            $this->db->query("update order_goods set refund_status=3 {$w[0]}",$w['1']);
        }

        #算临时关系
        $user = $this->db->find('user',$user_id);
        $gulijin_user_id = 0;
        if ($user['s_id']) {
            $gulijin_user_id = $user['s_id'];
        }else{
            $share_user = $this->db->find('user',$order_goods_no['gulijin_user_id']);
            if($share_user){
                if ($share_user['level']>0){
                    $gulijin_user_id = $order_goods_no['gulijin_user_id'];
                }
            }
        }
        #更新临时关系
        if ($gulijin_user_id) {
            $this->db->query("update user set last_share_id=?,relation_id=? where id=?",[$gulijin_user_id,$gulijin_user_id,$user_id]);
            $this->db->query("update order_goods_no set gulijin_user_id=? where id=?",[$gulijin_user_id,$order_goods_no['id']]);
        }
        #VIP及以上用户自己购买产品自己获得鼓励金
        if ($user['level']>0) {
            $this->db->query("update order_goods_no set gulijin_user_id=? where id=?",[$user_id,$order_goods_no['id']]);
        }

        $order_total_money = bcsub($order_goods_no['order_total_money'],$refund_money,2);
        $order_total_postage = bcsub($order_goods_no['order_total_postage'],$refund_postage,2);
        $order_total_points = bcsub($order_goods_no['order_total_points'],$refund_points,2);
        $order_total_use_points = bcsub($order_goods_no['order_total_use_points'],$refund_use_points,2);

        $order_total_lingshou = bcsub($order_goods_no['order_total_lingshou'],$refund_lingshou,2);
        $order_total_pifa = bcsub($order_goods_no['order_total_pifa'],$refund_pifa,2);
        $order_total_daili = bcsub($order_goods_no['order_total_daili'],$refund_daili,2);
        $order_total_gulijin = bcsub($order_goods_no['order_total_gulijin'],$refund_gulijin,2);

        #更新订单记录
        $mysql[] = $this->db->query("update order_goods_no set order_total_money=?,order_total_use_points=?,order_total_postage=?,order_total_points=?,order_total_lingshou=?,order_total_pifa=?,order_total_daili=?,order_total_gulijin=?,status=?,last_sh_time=? where id=?",[$order_total_money,$order_total_use_points,$order_total_postage,$order_total_points,$order_total_lingshou,$order_total_pifa,$order_total_daili,$order_total_gulijin,4,time(),$order_goods_no['id']]);
        
        #发放鼓励奖
        $mysql[] = m('Awardguli','c')->doit($order_no);
        #获得积分
        if($order_total_points > 0){
            $mysql[] = $order_id = m('Orderjifen','c')->add($com_order_no,$user_id,$order_total_points,1);
            $mysql[] =m('Userbill','xcom')->doit($com_order_no,$user_id,105,'order_jifen',$order_id,$order_total_points,'money_jf','购物赠送积分');
        }

        $msg = "确认收货";
        if ($refund_ids) $msg .= ",该订单存在退货订单ID[".implode(',',$refund_ids)."]";
        m('Log','xcom')->record($user_id, $msg, 'user');

        return $this->db->end($mysql);

    }

    /**
     * 余额支付
     * @param  [type] $order_no [description]
     * @return [type]           [description]
     */
    public function pay($order_no){
        //查询商品订单
        $map = [];
        $map[] = ["and", "order_no", "=", $order_no];
        $map[] = ["and", "pay_status", "=", 0];
        $w = where($map);
        $order_goods_list = $this->db->query("select * from order_goods $w[0]", $w[1]);
        if (empty($order_goods_list)) {
            return $this->setError('订单不存在!');
        }
        $userinfo = $this->db->query('select * from user where id = ?',[$order_goods_list[0]['user_id']],1);

        $map = [];
        $map[] = ["and", "order_no", "=", $order_no];
        $map[] = ["and", "status", "=", 1];
        $w = where($map);
        $order_goods_no = $this->db->query("select * from order_goods_no $w[0]", $w[1],1);
        $order_total_use_points = $order_goods_no["order_total_use_points"];
        $order_total_money = bcsub($order_goods_no["order_total_money"] , $order_total_use_points,2);
        //用户余额不足, 就去充值
        if ($userinfo["money_jf"] < $order_total_use_points) {
            $this->setError('积分不足!');
            return false;
        }
        //用户余额不足, 就去充值
        if ($userinfo["money"] < $order_total_money) {
            $need_money = $userinfo["money"]-$order_total_money;
            return $need_money;
        }

        $this->db->begin();
        $mysql = [];
        //修改订单支付状态
        $d = ["pay_status" => 1,'update_time'=>time()];
        $map = ['order_no=?', [$order_no]];
        $mysql[] = $this->db->update("order_goods", $d, $map);
        #更新订单记录
        $mysql[] = $this->db->update("order_goods_no", ['status'=>2,'pay_time'=>time()], ['order_no=?', [$order_no]]);
        //增加销量减库存
        foreach ($order_goods_list as $value){
            $mysql[] = $this->db->query("update goods set sales_volume=sales_volume+? where id=?",[$value["nums"],$value['goods_id']]);
            $mysql[] = $this->db->query("update goods_price set stock=stock-? where id=?",[$value["nums"],$value['goods_price_id']]);
        }
        //判断订单类型扣除积分或金额
        //抵扣积分
        if ($order_total_use_points>0) {
            $mysql[] = $jife_id = m('Orderjifen','c')->add($order_no,$userinfo['id'],-1*$order_total_use_points,4);
            $mysql[] = m('Userbill', 'xcom')->doit($order_no, $userinfo['id'], 200, 'order_jifen', $jife_id,$order_total_use_points,'money_jf','消费', 0);
        }
        //扣钱
        if ($order_total_money>0) {
            $mysql[] = m('Userbill', 'xcom')->doit($order_no, $userinfo['id'], 200, 'order_goods', $order_goods_list[0]['id'], $order_total_money,'money','消费', 0);
        }

        $rs = $this->db->end($mysql);
        if (!$rs) {
            $this->setError('支付失败!');
            return false;
        }
        return true;
    }

    #上传收货
    public function edit($data){
        //查询商品订单
        $map = [];
        $map[] = ["and", "id", "=", $data[0]];
        $w = where($map);
        $rs = $this->db->query("select * from order_goods $w[0]", $w[1],1);
        if (!$rs) {
            return $this->setError('订单不存在!');
        }

        //查询快递公司
        $kd_rs = $this->db->query("select * from express where kuaidi_no = ?", [$data[1]],1);
        if (!$kd_rs) {
            return $this->setError('快递公司不存在!');
        }

        #更新订单记录
        $result = $this->db->query("update order_goods set fahuo_status=1,kd_time=?,kd_no=?,kd_name=?,kd_code=? where id=? ",[time(),$data[2],$kd_rs['name'],$kd_rs['kuaidi_no'],$data[0]]);

        m('OrderGoods','c')->upfahuo($rs['order_no']);

        if (!$result) {
            return $this->setError('发货失败!');
        }
        return true;
    }

    //删除订单
    public function delete($user_id,$order_no){
        //查询商品订单
        $order_goods = $this->db->query("select * from order_goods where user_id=? and order_no=?",[$user_id,$order_no]);
        if (empty($order_goods)) {
            return $this->setError('订单不存在!');
        }

        $order_goods_no = $this->db->query("select * from order_goods_no where order_no = ?", [$order_no],1);
        if($order_goods_no['status'] != 1 ) return $this->setError("该订单状态不能删除!");

        $this->db->query("delete from order_goods where user_id=? and order_no=?",[$user_id,$order_no]);
        $this->db->query("delete from order_goods_no where user_id=? and order_no=?",[$user_id,$order_no]);
        m('Log','xcom')->record($user_id, '删除订单编号=>'.$order_no, 'user');
        return true;
    }
}
